package one.bugu.android.demon.ui.activity.wallet;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Color;
import android.text.Editable;
import android.text.InputFilter;
import android.text.SpannableString;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.juefeng.android.framework.LKUtil;
import com.juefeng.android.framework.common.util.ToastUtils;
import com.juefeng.android.framework.view.annotation.LKContentView;
import com.juefeng.android.framework.view.annotation.LKInjectView;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import one.bugu.android.demon.R;
import one.bugu.android.demon.bean.BGTInfoBean;
import one.bugu.android.demon.common.BaseHttpAsycResponceHandler;
import one.bugu.android.demon.common.MyBaseActivity;
import one.bugu.android.demon.constant.Constant;
import one.bugu.android.demon.constant.HttpConstant;
import one.bugu.android.demon.ui.dialog.CustomDialog;
import one.bugu.android.demon.ui.widget.BaseTopBarView;
import one.bugu.android.demon.util.ColorUtil;
import one.bugu.android.demon.util.DateUtils;
import one.bugu.android.demon.util.MyTextUtils;
import one.bugu.android.demon.util.PointLengthFilter;
import one.bugu.android.demon.util.PreferencesUtil;
import one.bugu.android.demon.util.StatusBarUtils;

/**
 * 提现页面
 */
@LKContentView(R.layout.activity_withdraw)
public class WithDrawActvity extends MyBaseActivity {

    /**
     * topBar
     */
    @LKInjectView(R.id.btbv_wd_charge)
    private BaseTopBarView btbv_wd_charge;
    /**
     * 地址输入
     */
    @LKInjectView(R.id.et_wd_address)
    private EditText et_wd_address;

    /**
     * 提现金额
     */
    @LKInjectView(R.id.et_wd_sum)
    private EditText et_wd_sum;

    /**
     * 手续费
     */
    @LKInjectView(R.id.tv_wd_charge)
    private TextView tv_wd_charge;

    /**
     * 全部转出按钮
     */
    @LKInjectView(R.id.tv_wd_all_charge_btn)
    private TextView tv_wd_all_charge_btn;

    /**
     * 备注
     */
    @LKInjectView(R.id.et_wd_remark)
    private TextView et_wd_remark;

    /**
     * 确认按钮
     */
    @LKInjectView(R.id.tv_charge_btn)
    private TextView tv_charge_btn;

    /**
     * 说明
     */
    @LKInjectView(R.id.tv_wd_explain)
    private TextView tv_wd_explain;

    public static final String ETH_DATA = "ethData";
    public static final int REMARK_MAX_LENGTH = 25;

    private String ethCount;
    /**
     * 输入标记
     */
    private boolean hasInputAddress = false;
    private boolean hasInputSum = false;


    @Override
    protected void initView() {
        super.initView();
        //设置状态栏
        StatusBarUtils.getInstance().setStatusBar(this, btbv_wd_charge);
        //设置
        et_wd_sum.setFilters(new InputFilter[]{new PointLengthFilter(5)});
    }

    @Override
    protected void initData() {
        super.initData();
        Intent intent = getIntent();
        if (intent != null) {
            ethCount = intent.getStringExtra(ETH_DATA);
        }
        getDrawFee();
    }

    @Override
    protected void initEvent() {
        super.initEvent();
        //topbar事件监听
        btbv_wd_charge.setEventInterface(new BaseTopBarView.EventInterface() {
            @Override
            public void leftOnClick() {
                finish();
            }

            @Override
            public void leftCloseClick() {

            }

            @Override
            public void rightOnClick() {

            }
        });
        //提现地址输入监听
        et_wd_address.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                String address = et_wd_address.getText().toString().trim();
                hasInputAddress = !TextUtils.isEmpty(address);
                tv_charge_btn.setSelected(hasInputAddress && hasInputSum);
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        //转账金额
        et_wd_sum.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                String inputNum = et_wd_sum.getText().toString().trim();
                if (inputNum.length() <= 0) {
                    return;
                }
                try {
                    double sum = Double.parseDouble(inputNum);
                    double ethNum = Double.parseDouble(ethCount);
                    if (sum > ethNum) {
                        ToastUtils.custom("余额不足");
                        String subNum = inputNum.substring(0, inputNum.length() - 1);
                        et_wd_sum.setText(subNum);
                        et_wd_sum.setSelection(subNum.length());
                    }
                    hasInputSum = !TextUtils.isEmpty(et_wd_sum.getText().toString().trim());
                } catch (Exception e) {
                    e.printStackTrace();
                    et_wd_sum.setText("");
                    hasInputSum = false;
                }
                tv_charge_btn.setSelected(hasInputAddress && hasInputSum);

            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        //备注
        et_wd_remark.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                String remark = et_wd_remark.getText().toString().trim();
                if (remark.length() <= 0) {
                    return;
                }
                if (remark.length() > REMARK_MAX_LENGTH) {
                    ToastUtils.custom("最多输入25个字");
                    remark = remark.substring(0, remark.length() - 1);
                    et_wd_remark.setText(remark);
                    et_wd_sum.setSelection(remark.length());
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        //全部转出
        tv_wd_all_charge_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                et_wd_sum.setText(ethCount);
            }
        });
        //确认转出
        tv_charge_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!tv_charge_btn.isSelected()) {
                    return;
                }
                String ethNum = et_wd_sum.getText().toString().trim();
                double aDouble = Double.parseDouble(ethNum);
                if (aDouble < 0.01) {
                    ToastUtils.custom(getResources().getString(R.string.str_wdt_draw_notify));
                    return;
                }
                String address = et_wd_address.getText().toString().trim();
                String pattern = "(0x)?[0-9a-fA-F]{40}";
                Pattern r = Pattern.compile(pattern);
                Matcher m = r.matcher(address);
                if (m.matches()) {
                    //合法钱包地址 显示弹窗
                    showEnsureDialog(address, ethNum);
                } else {
                    ToastUtils.custom(getResources().getString(R.string.str_charge_notify));
                }
            }
        });
    }

    /**
     * 获取提现手续费
     */
    private void getDrawFee() {
        String token = PreferencesUtil.getInstance().getString(this, Constant.TOKEN);
        Map<String, Object> map = new HashMap<>();
        map.put("token", token);
        map.put("wallteType", 50);
        LKUtil.getHttpManager().postBody(HttpConstant.GET_PROCEDURE, map, getDrawFeeHandler);
    }

    @SuppressLint("HandlerLeak")
    private BaseHttpAsycResponceHandler getDrawFeeHandler =
            new BaseHttpAsycResponceHandler<String>(true) {
                @Override
                public void onSuccess(String drawFee) {
                    super.onSuccess(drawFee);
                    //设置数据
                    setViewData(drawFee);
                }

                @Override
                public void onFailed(int code, String message) {
                    super.onFailed(code, message);
                    //设置默认提现费用
                    setViewData("0.0005");
                }

                @Override
                public void onError() {
                    super.onError();

                }
            };


    /**
     * 提交订单
     */
    private void getCharge(String address, String sum) {
        String token = PreferencesUtil.getInstance().getString(this, Constant.TOKEN);
        Map<String, Object> map = new HashMap<>();
        map.put("token", token);
        map.put("wallteAddr", address);
        map.put("applyValue", sum);
        map.put("wallteType", 50);
        map.put("remark", et_wd_remark.getText().toString().trim());
        LKUtil.getHttpManager().postBody(HttpConstant.WALLET_CHARGE, map, chargeHandler);
    }

    @SuppressLint("HandlerLeak")
    private BaseHttpAsycResponceHandler chargeHandler =
            new BaseHttpAsycResponceHandler<Object>(true) {
                @Override
                public void onSuccess(Object winInfo) {
                    super.onSuccess(winInfo);
                    ToastUtils.custom(getResources().getString(R.string.str_charge_success));
                    PreferencesUtil.getInstance().putBoolean(WithDrawActvity.this, "DRAW_SUC", true);
                    try {
                        BGTInfoBean bgtInfo = new BGTInfoBean();
                        bgtInfo.setWallteTypeName("ETH");
                        bgtInfo.setTradeTypeId("300");
                        bgtInfo.setTradeTypeName("提现");
                        bgtInfo.setOptNum(Double.parseDouble(et_wd_sum.getText().toString().trim()));
                        bgtInfo.setFlowDesc(et_wd_remark.getText().toString().trim());
                        bgtInfo.setCreateTime(DateUtils.getStrTime(System.currentTimeMillis(), DateUtils.FORMAT_YMDHMS));
                        bgtInfo.setWallteAddr(et_wd_address.getText().toString().trim());
                        //跳转支详情界面
                        Intent intent = new Intent(WithDrawActvity.this, WalletDetailsActivity.class);
                        intent.putExtra(WalletDetailsActivity.WALLET_DATA, bgtInfo);
                        startActivity(intent);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    finish();
                }

                @Override
                public void onFailed(int code, String message) {
                    super.onFailed(code, message);
                    ToastUtils.custom(message);
                }

                @Override
                public void onError() {
                    super.onError();

                }
            };


    /**
     * 设置界面数据
     */
    @SuppressLint("SetTextI18n")
    private void setViewData(String drawFee) {
        drawFee = subZeroAndDot(drawFee);
        tv_wd_charge.setText(getResources().getString(R.string.str_wd_draw_fee) + drawFee + "ETH");
        String explain = getResources().getString(R.string.str_wd_explain);
        String replace = explain.replace("EXPLAIN", drawFee);
        tv_wd_explain.setText(replace);
    }

    /**
     * 显示确认弹窗
     *
     * @param address 钱包地址
     * @param sum     转账金额
     */
    private void showEnsureDialog(final String address, final String sum) {
        final CustomDialog infoConfirmDialog = new CustomDialog(this);
        infoConfirmDialog.setCancelBtnText("取消");
        infoConfirmDialog.setConfirmBtnText("确认提现");
        infoConfirmDialog.setConfirmBtnColor(Color.parseColor("#5856D0"));
        View view = View.inflate(this, R.layout.dialog_charge_confirm_layout, null);
        TextView tv_dialog_count = view.findViewById(R.id.tv_dialog_count);
        TextView tv_dialog_expend = view.findViewById(R.id.tv_dialog_expend);
        infoConfirmDialog.setTopView(view);
        SpannableString countText = MyTextUtils.getInstance().setAutoTextColor("提现钱包地址：" + address, "(0x)?[0-9a-fA-F]{40}", "#5856D0");
        tv_dialog_count.setText(countText);
        SpannableString expendText = MyTextUtils.getInstance().setAutoTextColor("提现金额：" + sum + "ETH", "[0-9.]{1,}[A-Z]{1,}", "#5856D0");
        tv_dialog_expend.setText(expendText);

        infoConfirmDialog.setEventInterface(new CustomDialog.EventInterface() {
            @Override
            public void cancelOnClick() {
                infoConfirmDialog.dismiss();
            }

            @Override
            public void confirmOnClick() {
                infoConfirmDialog.dismiss();
                getCharge(address, sum);
            }
        });
        infoConfirmDialog.show();
    }

    /**
     * 格式化数据
     *
     * @param s
     * @return
     */
    public static String subZeroAndDot(String s) {
        if (s.indexOf(".") > 0) {
            //去掉多余的0
            s = s.replaceAll("0+?$", "");
            //如最后一位是.则去掉
            s = s.replaceAll("[.]$", "");
        }
        return s;
    }
}
